import 'package:flutter/material.dart';
import 'layer.dart';

class TextLayer extends Layer {
  Offset position;
  String text;
  double fontSize;

  bool _dragging = false;
  Offset? _dragStart;

  TextLayer({
    required this.position,
    required this.text,
    this.fontSize = 18,
  });

  @override
  bool hitTest(Offset p) {
    final tp = _createTextPainter();
    tp.layout();

    final rect = Rect.fromLTWH(position.dx, position.dy, tp.width, tp.height)
        .inflate(10); // 调整为更合适的固定值

    return rect.contains(p);
  }

  TextPainter _createTextPainter() {
    return TextPainter(
      text: TextSpan(
        text: text,
        style: TextStyle(
          color: Colors.white,
          fontSize: fontSize,
        ),
      ),
      maxLines: 1,
      textDirection: TextDirection.ltr,
    );
  }

  @override
  void paint(Canvas canvas, Size size) {
    final tp = _createTextPainter();
    tp.layout();
    tp.paint(canvas, position);

    if (selected) {
      final rect = Rect.fromLTWH(position.dx, position.dy, tp.width, tp.height);
      final borderPaint = Paint()
        ..color = Colors.orange
        ..style = PaintingStyle.stroke
        ..strokeWidth = 1;
      canvas.drawRect(rect.inflate(4), borderPaint); // 也可加 padding
    }
  }

  @override
  void onPanStart(Offset localPos, Size boundary) {
    if (hitTest(localPos)) {
      _dragging = true;
      _dragStart = localPos;
    }
  }

  @override
  void onPanUpdate(Offset localPos, Size boundary) {
    if (!_dragging || _dragStart == null) return;
    final delta = localPos - _dragStart!;
    final newOffset = position + delta;
    position = Offset(
      newOffset.dx.clamp(safeSpace, boundary.width - safeSpace),
      newOffset.dy.clamp(safeSpace, boundary.height - safeSpace),
    );
    _dragStart = localPos;
  }

  @override
  void onPanEnd(Size boundary) {
    _dragging = false;
    _dragStart = null;
    selected = false;
  }

  @override
  Offset getMetric() {
    // return _createTextPainter().height;
    return position;
  }
}
